package com.haven.webrobotserver.service.impl;

import com.haven.webrobotserver.dao.mybatis.mapper.MenuMapper;
import com.haven.webrobotserver.dao.mybatis.mapper.MenuitemMapper;
import com.haven.webrobotserver.domain.Menu;
import com.haven.webrobotserver.domain.Menuitem;
import com.haven.webrobotserver.domain.Role;
import com.haven.webrobotserver.domain.User;
import com.haven.webrobotserver.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MenuServiceImpl implements MenuService {

    @Autowired(required = false)
    private MenuitemMapper menuitemMapper;
    @Autowired(required = false)
    private MenuMapper menuMapper;

    @Override
    public List<Menuitem> getMenu() {

        List<Menuitem> menus = menuitemMapper.getMenu();


        return menus;
    }

    @Override
    public List<Menu> getUserMenus(User user) {

        Role role = user.getRole();
        List<Menu> menusByParentIdAndRole = getMenusByParentIdAndRole(0, role);

        return menusByParentIdAndRole;
    }

    private List<Menu> getMenusByParentIdAndRole(int parentId, Role role){
        List<Menu> result = menuMapper.getMenusByParentIdAndRole(parentId, role);

        if(result.size() != 0){

            for(Menu m: result){
                List<Menu> tmp = getMenusByParentIdAndRole(m.getId(), role);
                m.setChildrens(tmp);
            }
        }

        return result;
    }


}
